package maple.thelittleredbook.security;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import maple.thelittleredbook.common.util.JwtTokenUtil;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {

        // 获取Authorization请求头
        String header = request.getHeader("Authorization");

        // 检查是否存在Bearer token
        if (header != null && header.startsWith("Bearer ")) {
            // 提取token
            String token = header.substring(7);

            // 验证token
            if (jwtTokenUtil.validateToken(token)) {
                // 从token中获取用户信息
                Long userId = jwtTokenUtil.getUserIdFromToken(token);
                String role = jwtTokenUtil.getRoleFromToken(token);
                Boolean isActive = jwtTokenUtil.getIsActiveFromToken(token);

                // 只有激活的用户才能通过认证
                if (Boolean.TRUE.equals(isActive)) {
                    // 构建权限列表
                    List<SimpleGrantedAuthority> authorities = new ArrayList<>();
                    authorities.add(new SimpleGrantedAuthority("ROLE_" + role));

                    // 角色层级权限
                    if ("ADMIN".equals(role)) {
                        authorities.add(new SimpleGrantedAuthority("ROLE_USER"));
                    } else if ("SUPERADMIN".equals(role)) {
                        authorities.add(new SimpleGrantedAuthority("ROLE_USER"));
                        authorities.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
                    }

                    // 创建认证对象
                    UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
                            userId,
                            null,
                            authorities
                    );

                    // 设置认证结果到安全上下文
                    SecurityContextHolder.getContext().setAuthentication(authentication);
                }
            }
        }

        // 继续执行过滤器链
        filterChain.doFilter(request, response);
    }
}